"""Auth serve module"""
from typing import List, Optional

from dbgpt.component import SystemApp
from dbgpt_serve.core import BaseServe

from .api.endpoints import init_endpoints, router
from .config import (
    APP_NAME,
    SERVE_APP_NAME,
    SERVE_APP_NAME_HUMP,
    SERVE_CONFIG_KEY_PREFIX,
    SERVE_SERVICE_COMPONENT_NAME,
    ServeConfig,
)


class Serve(BaseServe):
    """Auth serve"""

    name = SERVE_APP_NAME

    def __init__(
        self,
        system_app: SystemApp,
        api_prefix: Optional[str] = f"/api/v1/serve/{APP_NAME}",
        api_tags: Optional[List[str]] = None,
        config: Optional[ServeConfig] = None,
    ):
        if api_tags is None:
            api_tags = [SERVE_APP_NAME_HUMP]
        super().__init__(
            system_app, api_prefix, api_tags, config or ServeConfig.from_app_config(
                system_app.config, SERVE_CONFIG_KEY_PREFIX
            )
        )
        self._config: ServeConfig = config or ServeConfig.from_app_config(
            system_app.config, SERVE_CONFIG_KEY_PREFIX
        )

    def init_app(self, system_app: SystemApp):
        if self._app_has_initiated:
            return
        self._system_app = system_app
        self._system_app.app.include_router(
            router, prefix=self._api_prefix, tags=self._api_tags
        )
        init_endpoints(self._system_app, self._config)
        self._app_has_initiated = True

    def on_init(self):
        """Called when init the application"""
        # Import entities to ensure they are registered
        from .models.models import (
            UserEntity,
            RoleEntity,
            MenuEntity,
            UserRoleEntity,
            RoleMenuEntity,
            DataPermissionEntity,
            LoginLogEntity,
            OperationLogEntity,
        )

    def before_start(self):
        """Called before starting the application"""
        pass
